package handler

import (
	"context"
	"dashenwo.com/dashenwo/micro_srv/user_srv/genpb"
	"dashenwo.com/dashenwo/micro_srv/user_srv/internal/service"
	"github.com/micro/go-micro/v2/errors"
	"github.com/micro/go-micro/v2/util/log"
)

type User struct {
	userService *service.UserService
}

// 用户登录接口
func (u User) Login(ctx context.Context, req *genpb.LoginRequest, rsp *genpb.LoginResponse) error {
	// 打印日志
	log.Log("Received User.Login request")
	user, err := u.userService.Login(req.Username, req.Password)
	if err != nil {
		return err
	} else if user == nil {
		return errors.New("com.dashenwo.srv.user", "用户名或密码错误", 200)
	}
	rsp.Token = "asdasdasda"
	return nil
}

func (u User) Register(ctx context.Context, req *genpb.RegisterRequest, rsp *genpb.RegisterResponse) error {
	// 打印日志
	log.Log("Received User.Register request")
	user, err := u.userService.Register(req.Nickname, req.Password, req.Phone, req.Code)
	if user != nil {
		rsp.Token = string(user.ID)
		return nil
	}
	return err
}

func NewUserHandler(userService *service.UserService) *User {
	return &User{
		userService: userService,
	}
}
